package com.ebelter.bodyfatscale.moudules.https;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.ebelter.bodyfatscale.ApplicationHelper;
import com.ebelter.bodyfatscale.moudules.https.interfaces.HttpResponse;
import com.ebelter.bodyfatscale.moudules.https.response.BaseResponse;
import com.ebelter.bodyfatscale.moudules.https.response.GetAverageResponse;
import com.ebelter.bodyfatscale.moudules.https.response.HostoryListData;
import com.ebelter.bodyfatscale.moudules.https.response.LoginResponse;
import com.ebelter.bodyfatscale.moudules.https.response.OriginalParametersResponse;
import com.ebelter.bodyfatscale.moudules.https.response.RegisterResponse;
import com.ebelter.bodyfatscale.moudules.https.response.ValidateEmailorNicknameResponse;
import com.ebelter.bodyfatscale.moudules.https.response.getEmailValidateCodeResponse;
import com.ebelter.bodyfatscale.moudules.update.UpdateVersionBean;
import com.ebelter.bodyfatscale.util.AppUtils;
import com.ebelter.bodyfatscale.util.GsonUtils;
import com.ebelter.btlibrary.util.ULog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class NetUtils {
    private static final String TAG = "NetUtils";
    private static NetUtils instance;
    private BaseJsonGenerator mBaseJsonGenerator;
    private NetUtils(){
        mBaseJsonGenerator=new BaseJsonGenerator();
    }
    public static NetUtils getInstance() {
        if (instance==null){
            synchronized (NetUtils.class){
                if (instance==null) instance=new NetUtils();
            }
        }
        return instance;
    }

    /**
     * 检测网络是否可用
     * @return true可用 false不可用
     */
    public static boolean available() {
        Context context = ApplicationHelper.mApplicationContecx;
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (NetworkInfo anInfo : info) {
                    if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                        if (anInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return true;
                        } else if (anInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            return true;
                        }
                    }
                }
            }
        }

        return false;
    }
    /**
     * get请求获取数据
     */
    public <T> void get(Object tag, String url,StringCallback callback){
        OkGo.get(url).tag(tag).execute(callback);
    }

    public void getFileDownLoad(Object tag, String url, FileCallback fileCallback){
        OkGo.get(url).tag(tag).execute(fileCallback);
    }


    public void cancelTag(Object tag){
        OkGo.getInstance().cancelTag(tag);
    }
    /**
     * post请求获取数据
     */
    public void post(Object tag, String url, StringCallback callback){
        post(tag,url,null,callback);
    }
    /**
     * post请求获取数据
     */
    public  void post(Object tag, String url, HttpParams httpParams, StringCallback callback){
        OkGo.post(url).tag(tag).params(httpParams).execute(callback);
    }

    /**
     * postString请求获取数据
     */
    public void postString(Object tag, String url, String requestString, StringCallback callback){
        OkGo.post(url).tag(tag).upString(requestString).execute(callback);
    }
    /**
     * postJson请求获取数据
     */
    public void postJson(Object tag, String url, String requestJson, StringCallback callback){
        OkGo.post(url).tag(tag).upJson(requestJson).execute(callback);
    }

    //-----------------------------------------------------------------------------------------------------------------------------

    static final String  R_S_R_S = "请求成功,解析成功";
    static final String  R_S_R_F = "请求成功，解析失败";
    static final String  R_F = "请求失败";

    //校验邮箱或者昵称 type=1 注册 type=2 忘记密码
    public void validateEmailorNicknameRequest(Object tag, final String validateStr, boolean isValidateEmail,
                                               final HttpResponse<ValidateEmailorNicknameResponse> httpResponse){
        postJson(tag, HttpsUrl.emailNicenameValidateUrl, mBaseJsonGenerator.getEmailorNicknameValidateRJ(validateStr, isValidateEmail),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        ValidateEmailorNicknameResponse res=GsonUtils.getInstance().fromJson(s,ValidateEmailorNicknameResponse.class);
                        if (res!=null){
                            res.validateStr=validateStr;
                            httpResponse.result(true,R_S_R_S,res);
                        }else {
                            httpResponse.result(false,R_S_R_F,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null);
                    }
                }
        );

    }

    //获取邮箱验证码 type=1 注册 type=2 忘记密码
    public void getEmailValidateCodeRequest(Object tag, String email, int type, final HttpResponse<getEmailValidateCodeResponse> httpResponse){
        postJson(tag, HttpsUrl.getEmailValidateCodeUrl, mBaseJsonGenerator.getEmailValidateRJ(email, type, AppUtils.getLocalStr()),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        getEmailValidateCodeResponse res=GsonUtils.getInstance().fromJson(s,getEmailValidateCodeResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res);
                        }else {
                            httpResponse.result(false,R_S_R_F,null);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null);
                    }
                }
        );
    }


    /**
     * 注册用户
     * @param birthday 1991-09-13
     * @param height 176
     * @param weight 65
     * @param code 邮箱验证码
     * @param type type=1 注册 type=2 忘记密码
     */
    public void registerRequest(Object tag, String nickName, String email, String password,
                                String birthday, int height, int weight, int sex,int profession,
                                String code, int type,
                                final HttpResponse<RegisterResponse> httpResponse){
        String registerjson=mBaseJsonGenerator.getRegisterRJ(nickName, email, password, birthday, height, weight,sex,profession, code, type);
        ULog.i(TAG,"注册Json："+registerjson);
        postJson(tag, HttpsUrl.registerUrl,registerjson ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        RegisterResponse res=GsonUtils.getInstance().fromJson(s,RegisterResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res);
                        }else {
                            httpResponse.result(false,R_S_R_F,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null);
                    }
                }
        );

    }


    /**
     *
     * 登录请求
     * @param isLoginEmail 是否是邮箱登录
     * @param loginStr 登录的字符串
     * @param psw MD5加密的密码
     * @param httpResponse 返回请求
     */
    public void loginRequest(Object tag, boolean isLoginEmail, String loginStr, String psw, final HttpResponse<LoginResponse> httpResponse){
        String loginRJ=mBaseJsonGenerator.getLoginRJ(isLoginEmail,loginStr,psw);
       // ULog.i(TAG,"登录的json："+loginRJ);
        postJson(tag,HttpsUrl.loginUrl,loginRJ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LoginResponse res=GsonUtils.getInstance().fromJson(s,LoginResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res);
                        }else {
                            httpResponse.result(false,R_S_R_F,null);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null);
                    }
                }
        );
    }


    //更新用户信息
    //"userId":"2af7b9c6139d4d5bbd960d503ad064b7", 这个字段必不可少
    public void updateInfo(Object tag, final Map<String,Serializable> paramMap, final HttpResponse<OriginalParametersResponse> httpResponse){
       String json=mBaseJsonGenerator.getMapRJ(paramMap);
       ULog.i(TAG,"--updateInfo--"+json);
        postJson(tag,HttpsUrl.updateInfoUrl,json,
               new StringCallback() {
                   @Override
                   public void onSuccess(String s, Call call, Response response) {
                       OriginalParametersResponse res = GsonUtils.getInstance().fromJson(s,OriginalParametersResponse.class);
                       if (res!=null){
                           res.originalParameters=paramMap;
                           httpResponse.result(true,R_S_R_S,res);
                       }else {
                           httpResponse.result(false,R_S_R_F,null);
                       }
                   }
                   @Override
                   public void onError(Call call, Response response, Exception e) {
                       super.onError(call, response, e);
                       httpResponse.result(false,R_F,null);
                   }
               }
       );
    }

    //更新用户信息
    //"userId":"2af7b9c6139d4d5bbd960d503ad064b7", 这个字段必不可少
    public void setTargetWeight(Object tag, final Map<String,Serializable> paramMap, final HttpResponse<OriginalParametersResponse> httpResponse){
        postJson(tag,HttpsUrl.setTargetWeight,mBaseJsonGenerator.getMapRJ(paramMap),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        OriginalParametersResponse res = GsonUtils.getInstance().fromJson(s,OriginalParametersResponse.class);
                        if (res!=null){
                            res.originalParameters=paramMap;
                            httpResponse.result(true,R_S_R_S,res);
                        }else {
                            httpResponse.result(false,R_S_R_F,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null);
                    }
                }
        );
    }

    //上传用户数据
    //"userId":"2af7b9c6139d4d5bbd960d503ad064b7", 这个字段必不可少
    public void uploadData(Object tag, final Map<String,Serializable> paramMap, final HttpResponse<OriginalParametersResponse> httpResponse){
        postJson(tag,HttpsUrl.uploadData,mBaseJsonGenerator.getMapRJ(paramMap),

                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        OriginalParametersResponse res = GsonUtils.getInstance().fromJson(s,OriginalParametersResponse.class);
                        if (res!=null){
                            res.originalParameters=paramMap;
                            httpResponse.result(true,R_S_R_S,res);
                        }else {
                            httpResponse.result(false,R_S_R_F,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null);
                    }
                }
        );
    }








    //更新密码
    public void findPassWord(Object tag, String email, String newPassword, String code, final HttpResponse<BaseResponse> httpResponse){
       // paramMap.put(HttpsParameters.USER_ID, UserSpUtil.readLong(Constants.IUser.USER_ID));
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("email",email);
        paramMap.put("newPassword",newPassword);
        paramMap.put("code",code);
        postJson(tag, HttpsUrl.updatePasswordUrl, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseResponse res=GsonUtils.getInstance().fromJson(s,BaseResponse.class);
                if (res!=null){
                    httpResponse.result(true,R_S_R_S,res);
                }else {
                    httpResponse.result(false,R_S_R_F,null);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                httpResponse.result(false,R_F,null);
            }

        });
    }

    public void getsHostoryListData(Object tag, Map<String,Serializable> paramMap, final HttpResponse<HostoryListData> httpResponse){
        postJson(tag, HttpsUrl.getHostoryDatas, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                ULog.i(TAG,"---getsHostoryListData---onSuccess()--"+s);
                HostoryListData hostoryListData=GsonUtils.getInstance().fromJson(s,HostoryListData.class);
                ULog.i(TAG,"---解析后的--"+hostoryListData);
                if (hostoryListData!=null){
                    httpResponse.result(true,MyAbsCallback.R_S_R_S,hostoryListData);
                }else {
                    httpResponse.result(false,MyAbsCallback.R_S_R_F,null);
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                e.printStackTrace();
                 ULog.i(TAG,"---getsHostoryListData---onError()--");
                httpResponse.result(false,MyAbsCallback.R_F,null);

            }
        });
    }


    //获取平均数 whichTime 1天2周3月
    public void getsAverageData(Object tag,int whichTime,final Map<String,Serializable> paramMap, final HttpResponse<GetAverageResponse> httpResponse){

        final String url;
        if (whichTime==1){
            url=HttpsUrl.getsAverageDay;
        }else if (whichTime==2){
            url=HttpsUrl.getsAverageWeek;
        }else if (whichTime==3){
            url=HttpsUrl.getsAverageMonth;
        }else {
            return;
        }


        postJson(tag, url, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                ULog.i(TAG,"---getsAverageData---onSuccess()--"+s);
                GetAverageResponse res= GsonUtils.getInstance().fromJson(s,GetAverageResponse.class);
                if (res!=null){
                    httpResponse.result(true,MyAbsCallback.R_S_R_S,res);
                }else {
                    httpResponse.result(false,MyAbsCallback.R_S_R_F,null);
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                e.printStackTrace();
               // ULog.i(TAG,"---getsAverageData---onError()--"+response.message());
                httpResponse.result(false,MyAbsCallback.R_F,null);
            }
        });


    }


    public void getVersionJosn(Object object,final HttpResponse<UpdateVersionBean> httpResponse){
        post(object, HttpsUrl.getVersionJson, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                ULog.i(TAG,"服务器上的json数据："+s);
                UpdateVersionBean res= GsonUtils.getInstance().fromJson(s,UpdateVersionBean.class);
                if (res!=null){
                    httpResponse.result(true,MyAbsCallback.R_S_R_S,res);
                }else {
                    httpResponse.result(false,MyAbsCallback.R_S_R_F,null);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                httpResponse.result(false,MyAbsCallback.R_F,null);
            }
        });
    }



}
